package com.vimi8.ebb.auth.api;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.vimi8.ebb.auth.configuration.HttpResponseEntity;
import com.vimi8.ebb.auth.dto.SignatureDto;
import io.swagger.annotations.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;


@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-11-15T13:08:37.350Z")

@Controller
public class SignatureApiController implements SignatureApi {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${oss.file.region}")
    private String region;
    @Value("${oss.file.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.file.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.file.bucket}")
    private String bucket;


    @Override
    public  HttpResponseEntity<SignatureDto> signaturePost(@ApiParam(value = "上传目录.", required = false) @RequestParam(value = "userDir", required = false) String userDir) {
        SignatureDto signatureDto=new SignatureDto();
        String postSignature=null;
        String host = "http://" + bucket + "." + region;
        OSSClient client = new OSSClient(region, accessKeyId, accessKeySecret);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, userDir);
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            postSignature = client.calculatePostSignature(postPolicy);
            signatureDto.setAccessid(accessKeyId);
            signatureDto.setDir(userDir);
            signatureDto.setExpire(expiration.getTime()/1000+"");
            signatureDto.setHost(host);
            signatureDto.setSignature(postSignature);
            signatureDto.setPolicy(encodedPolicy);
        } catch (Exception e) {
            logger.info("signaturePost error "+e.getMessage());
        }
        return new HttpResponseEntity<SignatureDto>(signatureDto, HttpStatus.OK);
    }
}
